package fr.mystnihon.game.model.graphic;

import java.util.ArrayList;

import android.graphics.Rect;

/**
 * 
 * @author The book
 * 
 */
public class Animation {
	private final ArrayList<AnimFrame> frames;
	private int curFrameIndex;
	private long animTime;
	private long totalDuration;

	/**
	 * Create an new empty animation.
	 */
	public Animation() {
		frames = new ArrayList<AnimFrame>();
		totalDuration = 0L;
		start();
	}

	public synchronized void addFrame(long duration, int posX, int posY,
			int width, int height) {
		totalDuration += duration;
		frames.add(new AnimFrame(totalDuration, posX, posY, width, height));
	}

	/**
	 * Start this animation over from the beginning.
	 */
	public synchronized void start() {
		animTime = 0;
		curFrameIndex = 0;
	}

	/**
	 * Update this animation's current image (frame) , if necessary.
	 * 
	 * @param elapsedTime
	 */
	public synchronized void update(long elapsedTime) {
		if (frames.size() > 1) {
			animTime += elapsedTime;

			if (animTime >= totalDuration) {
				animTime = animTime % totalDuration;
				curFrameIndex = 0;

			}

			while (animTime > getFrame(curFrameIndex).endTime) {
				curFrameIndex++;
			}
		}
	}

	// Optimize.
	public synchronized Rect getRectangle() {
		if (frames.size() == 0) {
			return null;
		} else {
			return new Rect(getFrame(curFrameIndex).x,
					getFrame(curFrameIndex).y, getFrame(curFrameIndex).x
							+ getFrame(curFrameIndex).width,
					getFrame(curFrameIndex).y + getFrame(curFrameIndex).height);

		}
	}

	/**
	 * Get the specified frame
	 * 
	 * @param index
	 * @return AnimFrame
	 */
	public AnimFrame getFrame(int index) {
		return frames.get(index);
	}

	class AnimFrame {

		public long endTime;

		public int x = 0;
		public int y = 0;
		public int width = 0;
		public int height = 0;

		public AnimFrame(long endTime, int x, int y, int width, int height) {
			this.endTime = endTime;

			this.x = x;
			this.y = y;
			this.width = width;
			this.height = height;
		}

	}
}
